package com.design_patterns.proxy;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Random;

/**
 * @author: 李德才
 * @description:
 * @create: 2020-08-30 19:51
 **/
public class CglibMain {

    public CglibMain(){

    }

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Brush.class);
        enhancer.setCallback(new BrushInterceptor());
        Brush brush = (Brush) enhancer.create();
        brush.drawing();
    }

    /**
     * 没有和任何业务对象绑定，可以灵活使用
     */
    static class BrushInterceptor implements MethodInterceptor {
        public BrushInterceptor(){

        }

        @Override
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println(o.getClass().getSuperclass().getName());
            System.out.println("before");
            Object result = methodProxy.invokeSuper(o, objects);
            System.out.println("after");
            return result;
        }
    }

    class Brush {
        public Brush(){

        }

        public void drawing() {
            System.err.println("画笔开始画画");
            try {
                Thread.sleep(new Random().nextInt(5000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.err.println("画笔绘画完成");
        }
    }

}
